package com.dk.academic.controller;

import com.dk.academic.controller.base.SuperController;
import com.dk.academic.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * @Author: 廉雪峰
 * @Date: 2019/1/10 16:32
 * @Version 1.0
 */
@Controller
public class LoginController extends SuperController {

    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public String index() {
        return "login";
    }

    @RequestMapping("/dologin")
    public String doLogin(@RequestParam("username") String username, @RequestParam("password") String password, Model model) {
        // 处理登录逻辑
        // 从SecurityUtils里边创建一个 subject
        Subject subject = SecurityUtils.getSubject();
        // 在认证提交前准备 token（令牌）
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        // 执行认证登陆
        try {
            subject.login(token);
        } catch (AccountException e) {
            // 如果登录失败，返回失败信息
            model.addAttribute("msg", e.getMessage());
            return "/login";
        }
        //根据权限，指定返回数据
        String role = userService.getRole(username);
        // 用session记住当前登录用户，方便获取
        session.setAttribute("CurrentUser", token.getUsername());
        if ("customer".equals(role)) {
            return "redirect:/";
        }
        if ("admin".equals(role)) {
            return "redirect:/admin/index";
        }
        return "/";
    }

    // 退出登录
    @RequestMapping("/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        System.out.println("执行退出操作");
        session.removeAttribute("CurrentUser");
        return "redirect:/";
    }
}
